# -*- coding: utf-8 -*-
"""
@Author: HuangYu
@E-mail: huangyu@dinton.cn
"""
import traceback

from django.db import connection
from django.http import JsonResponse

from apps.archive_cabinets.dataview.sql.mysql import (
    edit_cabinet_sql as edit_sql
)
from apps.common.errorcode import response_error, operate_error


# Create your views here.
def edit_cabinet(request):
    """档案柜编辑接口"""
    ret = dict(errCode=0, errMsg=operate_error[0])
    cursor = connection.cursor()
    try:
        if request.method == 'POST':
            params = request.POST
            cabinet_id = params.get('id')
            cabinet_code = params.get('code')
            admin_id = params.get('admin')
            storage_location = params.get('storage_location')
            remark = params.get('remark')
            material = params.get('material')
            lattice_count = params.get('lattice_count')

            # 档案柜编号空值校验
            if not cabinet_code:
                ret['errCode'] = 20002
                ret['errMsg'] = operate_error[20002] \
                    + u': 参数档案柜参数不能为空'
                return JsonResponse(ret)

            # 档案柜id有效性校验
            try:
                cabinet_id = int(cabinet_id)
            except:
                cabinet_id = cabinet_id
            cab_query_sql = edit_sql.QUERY_CABINET
            content = ' AND `id` = %s'
            cursor.execute(cab_query_sql + content, (cabinet_id,))
            cabinet_query = cursor.fetchone()
            if not cabinet_query:
                ret['errCode'] = 20002
                ret['errMsg'] = operate_error[20002] + u': 该档案柜不存在'
                return JsonResponse(ret)

            # 档案柜编号唯一性校验
            content = ' AND `id` <> %s AND `code` = %s'
            cursor.execute(cab_query_sql + content, (cabinet_id, cabinet_code))
            cabinet_query = cursor.fetchone()
            if cabinet_query:
                ret['errCode'] = 20002
                ret['errMsg'] = operate_error[20002] \
                    + u': 该档案柜编号已经存在'
                return JsonResponse(ret)

            # 管理员id有效性校验
            try:
                admin_id = int(admin_id)
            except:
                admin_id = admin_id
            admin_sql = edit_sql.QUERY_AUTHOR
            content = ' AND `id` = %s'
            cursor.execute(admin_sql + content, (admin_id,))
            admin_query = cursor.fetchone()
            if not admin_query:
                ret['errCode'] = 20002
                ret['errMsg'] = operate_error[20002] \
                    + u': 管理员不存在，请重新选择'
                return JsonResponse(ret)

            # 档案隔档个数验证
            lattice_query_sql = edit_sql.QUERY_LATTICE_COUNT
            content = ' AND `cabinet_id` = %s'
            cursor.execute(lattice_query_sql + content, (cabinet_id,))
            try:
                lattice_count = int(lattice_count)
            except Exception as e:
                traceback.print_exc()
                ret['errCode'] = 20002
                ret['errMsg'] = operate_error[20002] \
                    + u': 参数隔档数必须为整数'
                return JsonResponse(ret)

            fetch_ret = cursor.fetchone()
            _lattice_count = fetch_ret[0] if fetch_ret else 0
            new_count = lattice_count - _lattice_count
            if new_count < 0:
                ret['errCode'] = 20002
                ret['errMsg'] = operate_error[20002] \
                    + u'参数隔档个数必须大于原有隔档个数(%s)' % _lattice_count
                return JsonResponse(ret)

            for i in range(new_count):
                lattice_code = (3 - len(str(i))) * '0' + str(i) \
                    if (3 - len(str(i))) >= 0 else str(i)
                insert_sql = edit_sql.INSERT_LATTICE
                insert_params = (lattice_code, cabinet_id)
                cursor.execute(insert_sql, insert_params)

            # 更新档案柜基本属性
            set_sql = edit_sql.SET_CABINET
            content = ' AND `id` = %s'
            set_params = (
                cabinet_code, material, storage_location, remark, admin_id,
                cabinet_id
            )
            cursor.execute(set_sql + content, set_params)
        else:
            ret['errCode'] = 405
            ret['errMsg'] = response_error['405']
    except Exception as e:
        traceback.print_exc()
        ret['errCode'] = 20001
        ret['errMsg'] = operate_error[20001] + ': ' + str(e)
    return JsonResponse(ret)


def edit_box(request):
    """档案盒基本属性编辑接口"""
    ret = dict(errCode=0, errMsg=operate_error[0])
    cursor = connection.cursor()
    try:
        if request.method == 'POST':
            params = request.POST
            box_id = params.get('id')
            box_code = params.get('code')
            specifications = params.get('specifications')
            remark = params.get('remark')

            # 档案盒id有效性校验
            try:
                box_id = int(box_id)
            except:
                box_id = box_id
            box_query_sql = edit_sql.QUERY_BOX
            content = ' AND `id` = %s'
            cursor.execute(box_query_sql + content, (box_id,))
            box_row = cursor.fetchone()
            if not box_row:
                ret['errCode'] = 20002
                ret['errMsg'] = operate_error[20002] + u': 档案盒不存在'
                return JsonResponse(ret)

            # 档案盒编号唯一性校验
            content = ' AND `id` <> %s AND `code` = %s'
            cursor.execute(box_query_sql + content, (box_id, box_code))
            box_row = cursor.fetchone()
            if box_row:
                ret['errCode'] = 20002
                ret['errMsg'] = operate_error[20002] + \
                    u': 参数档案盒编号已存在'
                return JsonResponse(ret)

            # 更新档案盒基本属性
            set_sql = edit_sql.SET_BOX
            content = ' AND `id` = %s'
            set_params = (box_code, specifications, remark, box_id)
            cursor.execute(set_sql + content, set_params)
        else:
            ret['errCode'] = 405
            ret['errMsg'] = response_error['405']
    except Exception as e:
        traceback.print_exc()
        ret['errCode'] = 20001
        ret['errMsg'] = operate_error[20001] + ': ' + str(e)
    return JsonResponse(ret)
